import { NCarousel } from "naive-ui";

import type {
  CarouselProps,
  CarouselArrowSlotProps,
  CarouselDotSlotProps,
  CarouselInst,
} from "naive-ui";
import type { OmitHTMLAttributes, BaseComponentType } from "../types";
import { getSlotsDom } from "../utils";

export type CarouselFactoryConstructorType = {
  props?: CarouselProps;
  attrs?: OmitHTMLAttributes<"draggable">;
  defaultSlot?: BaseComponentType;
  arrowSlot?: (v?: CarouselArrowSlotProps) => BaseComponentType;
  dotSlot?: (v?: CarouselDotSlotProps) => BaseComponentType;
};
export class CarouselFactory {
  private props: CarouselProps = {};
  private attrs: OmitHTMLAttributes<"draggable"> = {};
  private arrowSlot: (v?: CarouselArrowSlotProps) => BaseComponentType = () =>
    null;
  private defaultSlot: BaseComponentType = null;
  private dotSlot: (v?: CarouselDotSlotProps) => BaseComponentType = () => null;
  private domRef: CarouselInst | null = null;

  constructor(data?: CarouselFactoryConstructorType) {
    if (data?.props) this.setProps(data.props);
    if (data?.attrs) this.setAttrs(data.attrs);
    if (data?.defaultSlot) this.setDefault(data.defaultSlot);
    if (data?.arrowSlot) this.setArrow(data.arrowSlot);
    if (data?.dotSlot) this.setDot(data.dotSlot);
  }

  setAttrs(attrs: OmitHTMLAttributes<"draggable">) {
    this.attrs = attrs;
    return this;
  }
  setProps(props: CarouselProps) {
    this.props = props;
    return this;
  }
  setDefault(component: BaseComponentType) {
    this.defaultSlot = component;
    return this;
  }
  setArrow(component: (v?: CarouselArrowSlotProps) => BaseComponentType) {
    this.arrowSlot = component;
    return this;
  }
  setDot(component: (v?: CarouselDotSlotProps) => BaseComponentType) {
    this.dotSlot = component;
    return this;
  }

  getCurrentIndex() {
    return this.domRef?.getCurrentIndex() ?? 0;
  }

  prev() {
    this.domRef?.prev();
  }

  next() {
    this.domRef?.next();
  }

  to(index: number) {
    this.domRef?.to(index);
  }

  create() {
    return (
      <NCarousel
        ref={(el: HTMLElement) => {
          this.domRef = el as unknown as CarouselInst;
        }}
        {...this.attrs}
        {...this.props}
      >
        {{
          default: () => getSlotsDom(this.defaultSlot),
          arrow: (info: CarouselArrowSlotProps) =>
            getSlotsDom(this.arrowSlot(info)),
          dots: (info: CarouselDotSlotProps) => getSlotsDom(this.dotSlot(info)),
        }}
      </NCarousel>
    );
  }
}
